package core;

import fileoperation.FileDeletion;
import gitobject.GitObject;
import repository.Repository;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class JitBranch {
    static String branchFilePath = Repository.getGitDir()+ File.separator+"refs"+File.separator+"heads";

    /**
     * Print all the branches.
     * @throws Exception
     */
    public static void printBranch() throws IOException {
        String currentBranch = getHEAD();

        File[] fs = new File(branchFilePath).listFiles();
        if (fs.length == 0) { // if nothing has been committed yet, just print master branch
            System.out.println("* master");
            return;
        }
        for (File f:fs) {
            String branch = f.getName();
            if (branch.equals(currentBranch)) {
                System.out.println("* "+branch);
            }
            else {
                System.out.println("  "+branch);
            }
        }
    }

    /**
     * Check if a branch exists.
     * @return boolean
     * @throws Exception
     */
    public static boolean branchExists(String branchName) {
        File[] fs = new File(branchFilePath).listFiles();
        for (File f:fs) {
            String branch = f.getName();
            if (branch.equals(branchName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Delete a branch if exists.
     * @throws Exception
     */
    public static void deleteBranch(String branchName) throws IOException {
        if (getHEAD().equals(branchName)) {
            System.out.println("error: Cannot delete branch '" + branchName + "' currently checked out at working directory.");
            return;
        }
        if (branchExists(branchName)) {
            FileDeletion.deleteFile(branchFilePath+File.separator+branchName);
        }
    }

    /**
     * Create a new branch.
     * @throws Exception
     */
    public static void createBranch(String branchName) throws IOException {
        String current = getHEAD();
        String commitId = GitObject.getValue(new File(branchFilePath+File.separator+current));

        File branchFile = new File(branchFilePath+File.separator+branchName);
        if (!branchExists(branchName)) branchFile.createNewFile();
        FileWriter fw = new FileWriter(branchFile, false);
        fw.write(commitId);
        fw.close();
    }

    /**
     * Get current branch name from HEAD.
     * @return String
     * @throws Exception
     */
    public static String getHEAD() throws IOException {
        File HEAD = new File(Repository.getGitDir() + File.separator + "HEAD");
        String path = GitObject.getValue(HEAD).substring(5).replace("\n", ""); // refs/heads/master
        String current = path.substring(path.indexOf(File.separator, path.indexOf(File.separator)+1)+1);
        return current;
    }
}
